package com.yjhb.android.sbz.v2.activity

import android.graphics.Paint
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.viewpager.widget.PagerAdapter
import com.alibaba.fastjson.JSONArray
import com.alibaba.fastjson.JSONObject
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.yjhb.android.sbz.App
import com.yjhb.android.sbz.R
import com.yjhb.android.sbz.activity.BaseActivity
import com.yjhb.android.sbz.tool.EventMsg
import com.yjhb.android.sbz.mvp.vip.VipPresenter
import com.yjhb.android.sbz.mvp.vip.VipView
import com.yjhb.android.sbz.tool.Tool
import com.yjhb.android.sbz.v2.mvp.presenter.ConfigPresenter
import com.yjhb.android.sbz.v2.mvp.view.ConfigView
import com.jojo.android.zxlib.tool.ZxTimeTool
import com.jojo.android.zxlib.tool.ZxToast
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet.BottomListSheetBuilder
import kotlinx.android.synthetic.main.activity_v2_vip.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.sufficientlysecure.htmltextview.HtmlHttpImageGetter
import org.sufficientlysecure.htmltextview.HtmlTextView


/**
 *  创建者 zx
 *  创建时间 2021/5/18 15:49
 */
class V2VipActivity : BaseActivity<VipPresenter>(), ConfigView, VipView {

    private val configPresenter = lazy { ConfigPresenter(this) }
    private var config: JSONArray? = null

    override fun initPresenter() = VipPresenter(this)

    override fun getLayoutId() = R.layout.activity_v2_vip

    override fun initUI() {
        tabLayout?.setDefaultNormalColor(resources.getColor(R.color.gray_66))
        tabLayout?.setDefaultSelectedColor(resources.getColor(R.color.vip_color))
    }

    override fun initData() {
        configPresenter.value.getSysConfig("MemberTab")
    }

    override fun regEvent() {
        back?.setOnClickListener { finish() }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun eventMsg(msg: EventMsg) {
        if (msg.msg === EventMsg.USER_UPDATE_OK) {
            update()
        }
    }

    fun update() {
        try {
            App.userInfo?.let {
                Glide.with(this).load(it.avatar).apply(RequestOptions().placeholder(R.mipmap.test_head)).into(user_head_iv)
                config?.let { conf ->
                    for (c in conf.indices) {
                        val data = conf.getJSONObject(c)?.getJSONObject("content")
                        val vipLevel = data?.getIntValue("vipLevel")
                        if (vipLevel == it.vipLevel) {
                            user_type_tv?.text = data.getString("name")
                            break
                        }
                        if (c == conf.lastIndex){
                            user_type_tv?.text = "普通会员"
                        }
                    }

                }
                if (it.vipLevel == 0) {
                    expired_date_tv.text = "到期时间：无"
                } else {
                    expired_date_tv.text = "到期时间：" + ZxTimeTool.getDate(it.vipEndTime.time,
                            "yyyy年MM月dd日")
                }
            }

        } catch (e: Exception) {
        }
    }


    override fun onConfig(config: JSONObject?) {

    }

    override fun onConfig(config: JSONArray?) {
        this.config = config
        update()
        viewpager?.adapter = pagerAdapter
        tabLayout?.setupWithViewPager(viewpager)
    }

    override fun onSuccess(data: Any?) {
        loadingDialog.cancel()
        EventBus.getDefault().post(EventMsg(EventMsg.REQUEST_USER_UPDATE, null))
        ZxToast.showSuccessBottomToast("开通成功！")
    }

    override fun onFailure(code: Int, msg: String?) {
        loadingDialog.cancel()
        ZxToast.showINFOBottomToast(msg)
    }

    override fun onWait() {
        loadingDialog.show()
    }


    private val pagerAdapter: PagerAdapter = object : PagerAdapter() {

        override fun getCount(): Int {

            return (if (config == null) 0 else config?.size)!!
        }

        override fun isViewFromObject(view: View, o: Any): Boolean {
            return view === o
        }

        override fun instantiateItem(container: ViewGroup, position: Int): Any {
            val v = LayoutInflater.from(activity).inflate(R.layout.layout_v2_vip, null, false)
            val data = config?.getJSONObject(position)?.getJSONObject("content")
            data?.let {
                val vipLevel = it.getIntValue("vipLevel")
                v.findViewById<TextView>(R.id.name_tv)
                        .text = it.getString("name")
                v.findViewById<TextView>(R.id.date_tv)
                        .text = (it.getString("day") ?: "永久")
                val contentTv = v.findViewById<HtmlTextView>(R.id.content_tv)
                contentTv.setHtml(it.getString("rule"), HtmlHttpImageGetter(contentTv))

                v.findViewById<TextView>(R.id.tips_tv)
                        .text = it.getString("tip")
                val oldTv = v.findViewById<TextView>(R.id.old_tv)
                if (TextUtils.isEmpty(it.getString("originPrice"))) {
                    oldTv.visibility = View.INVISIBLE
                } else {
                    oldTv.visibility = View.VISIBLE
                    oldTv.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
                    oldTv.text = it.getString("originPrice")
                }

                val priceTv = v.findViewById<TextView>(R.id.new_tv)
                val price = it.getString("price")
                val vipPrice = it.getString("vipPrice")
                if (TextUtils.isEmpty(price)) {
                    priceTv.visibility = View.INVISIBLE
                } else {
                    priceTv.visibility = View.VISIBLE
                    priceTv.text = price
                    priceTv.setOnClickListener { view ->

                        BottomListSheetBuilder(activity, false)
                                .addItem(R.mipmap.vip_yue, "余额支付", "yue")
                                .addItem(R.mipmap.vip_pay, "支付宝/微信支付", "pay")
                                .setTitle("付款方式")
                                .setOnSheetItemClickListener { dialog, itemView, position, tag ->
                                    if (position == 0) {
                                        presenter.balanceToVip(vipLevel)
                                        dialog.dismiss()
                                    } else if (position == 1) {
                                        Tool.startRechargeActivity(activity, 4, vipPrice, true)
                                        dialog.dismiss()
                                    }
                                }
                                .build()
                                .show()
                    }
                }


                val expiredateTv = v.findViewById<TextView>(R.id.expireDate_tv)

                App.userInfo?.let { user ->
                    if (user.vipLevel == vipLevel) {
                        if (App.userInfo!!.vipLevel == 0) {
                            expiredateTv.text = "到期时间：无"
                        } else {
                            expiredateTv.text = "到期时间：" + ZxTimeTool.getDate(user.vipEndTime.time,
                                    "yy年MM月dd日")
                        }
                    } else {
                        if (vipLevel == 0) {
                            expiredateTv.text = "到期时间：无"
                        } else {
                            expiredateTv.text = "未开通"
                        }
                    }
                }

            }
            container.addView(v)
            return v
        }

        override fun destroyItem(container: ViewGroup, position: Int, any: Any) {
            container.removeView(any as View)
        }

        override fun getPageTitle(position: Int): CharSequence? {
            return config?.getJSONObject(position)?.getString("tab")
        }
    }
}